import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

class _YkPluginType {
  _YkPluginType._();

  static String ykDebugTest = "yk_debug_test";
  static String ykAlert = "yk_alert";
  static String ykStartLiveActivity = "yk_start_live_activity";
  static String ykStopLiveActivity = "yk_stop_live_activity";
  static String ykReloadWidget = "yk_reload_widget";
  static String ykUpdateLiveActivity = "yk_update_live_activity";
}

mixin YkPluginDelegate {

  Future<void> setup();

  Future<dynamic> callHandler(String name, dynamic params);
}

class YkPlugin {
  // 私有构造函数
  YkPlugin._privateConstructor();

  // 静态实例
  static final YkPlugin _instance = YkPlugin._privateConstructor();

  // 获取单例实例的方法
  static YkPlugin get instance => _instance;

  MethodChannel? _methodChannel;

  YkPluginDelegate? _delegate;

  Future<void> setup({required YkPluginDelegate delegate}) {
    _delegate = delegate;
    _methodChannel = const MethodChannel('yk_plugin');
    _getChannel()?.setMethodCallHandler((call) async {
      return _delegate?.callHandler(call.method, call.arguments) ?? Future.value();
    });
    return delegate.setup();
  }

  Future<String?> debug() {
    return _getChannel()?.invokeMethod<String?>(_YkPluginType.ykDebugTest) ?? Future.value(null);
  }

  Future<dynamic> alert({required String? title, required String? msg, String? confirmBtnText, String? cancelBtnText}) {
    return _getChannel()?.invokeMethod<dynamic>(_YkPluginType.ykAlert, {
      "title": title,
      "msg": msg,
      "confirmBtnText": confirmBtnText,
      "cancelBtnText": cancelBtnText
    }) ?? Future.value();
  }

  Future<dynamic> startLiveActivity() {
    return _getChannel()?.invokeMethod(_YkPluginType.ykStartLiveActivity, {}) ?? Future.value();
  }

  Future<dynamic> stopLiveActivity() {
    return _getChannel()?.invokeMethod(_YkPluginType.ykStopLiveActivity, {}) ?? Future.value();
  }

  Future<dynamic> reloadWidget() {
    return _getChannel()?.invokeMethod(_YkPluginType.ykReloadWidget, {}) ?? Future.value();
  }

  Future<dynamic> updateLiveActivity() {
    return _getChannel()?.invokeMethod(_YkPluginType.ykUpdateLiveActivity, {}) ?? Future.value();
  }

  MethodChannel? _getChannel() {
    assert(_methodChannel != null, "请先预加载  setup()");
    return _methodChannel;
  }
}


